﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using System.Security;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Configuration;
using System.IO;
namespace Sync_Email_to_SharePoint
{
    public partial class Config_Sharepoint : System.Windows.Forms.Form
    {
        Sharepoint_Reference.Lists Service = new Sharepoint_Reference.Lists();
        Sharepoint_ViewReference.Views Listview = new Sharepoint_ViewReference.Views();
        string xmlfilepath;
        public Config_Sharepoint()
        {
            InitializeComponent();
        }

        private void LoginSharePoint_Click(object sender, EventArgs e)
        {
            try
            {
                List<int > li = new List<int >();
                var targetSite = new Uri(SharepointURL.Text.ToString());
                var login = SharepointUsername.Text.ToString();
                var password = Sharepointpassword.Text.ToString();
                var securePassword = new SecureString();
                foreach (char c in password)
                {
                    securePassword.AppendChar(c);
                }

                var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

                Service.Url = SharepointURL.Text.ToString() + "/_vti_bin/lists.asmx";
                Service.UseDefaultCredentials = false;
                string authCookieValue = onlineCredentials.GetAuthenticationCookie(targetSite);
                Service.CookieContainer = new CookieContainer();
                Service.CookieContainer.Add(new Cookie("FedAuth", authCookieValue.TrimStart("SPOIDCRL=".ToCharArray()), String.Empty, targetSite.Authority));
                var claimsLogin = "i:0#.f|membership|" + login;

                Listview.Url = SharepointURL.Text.ToString() + "/_vti_bin/views.asmx";
                Listview.UseDefaultCredentials = false;
                string authCookieValue1 = onlineCredentials.GetAuthenticationCookie(targetSite);
                Listview.CookieContainer = new CookieContainer();
                Listview.CookieContainer.Add(new Cookie("FedAuth", authCookieValue1.TrimStart("SPOIDCRL=".ToCharArray()), String.Empty, targetSite.Authority));
                var claimsLogin1 = "i:0#.f|membership|" + login;

                XmlNode lists = Service.GetListCollection();
                foreach (XmlNode list in lists)
                {
                    Sharepointlist.Items.Add(list.Attributes["Title"].Value);
                }
                Sharepointlist.Enabled = true;

                xmlfilepath = Path.GetFullPath("UserDetails.xml");
                XDocument xmlDoc = XDocument.Load(Path.GetFullPath(xmlfilepath));
                var IDvalue = xmlDoc.Descendants("ID");
                foreach (var item in IDvalue)
                {
                   li.Add(Convert.ToInt32(item.Value));
                }
                var q = (from p in xmlDoc.Descendants("User")
                         where Convert.ToInt32(p.Element("ID").Value) == li.Max()
                         select p).First();
                q.Element("URL").Value = SharepointURL.Text.ToString();
                q.Element("Username").Value = SharepointUsername.Text.ToString();
                q.Element("password").Value = Sharepointpassword.Text.ToString();

                xmlDoc.Save(Path.GetFullPath(xmlfilepath));

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Config_Sharepoint_Load(object sender, EventArgs e)
        {
            Sharepoint_next.Enabled = false;
            Sharepointlist.Enabled = false;
        }

        private void Sharepointlist_SelectedIndexChanged(object sender, EventArgs e)
        {
            Sharepoint_next.Enabled = true;
        }

        private void Sharepoint_next_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XmlNode xnNewFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");
                xnNewFields.InnerXml +=
                "<Method ID='1'>" +
                "<Field Type='Text' Title='From' DisplayName = 'From' Required='TRUE' Description = 'Enter the Name'/>" +
                "</Method>";
                xnNewFields.InnerXml +=
                "<Method ID='2'>" +
                "<Field Type='Text' DisplayName='CC'/>" +
                "</Method>";
                xnNewFields.InnerXml +=
                "<Method ID='3'>" +
                "<Field Type='Text' DisplayName='BCC'/>" +
                "</Method>";
                XmlNode xnProperties = xmlDoc.CreateNode(XmlNodeType.Element, "List", "");
                XmlAttribute xnEnableversioningAttribute = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "EnableVersioning", "");
                xnEnableversioningAttribute.Value = "True";
                xnProperties.Attributes.Append(xnEnableversioningAttribute);
                XmlNode updateList = Service.UpdateList(Sharepointlist.SelectedItem.ToString(), xnProperties, xnNewFields, null, null, null);
                XmlNode xnDefaultView = Listview.GetView(Sharepointlist.SelectedItem.ToString(), "");
                string sDefaultViewName = xnDefaultView.Attributes["Name"].Value.ToString();
                XmlNode xnViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
                foreach (XmlNode childNode in xnDefaultView.ChildNodes)
                {
                    if (childNode.Name == "ViewFields")
                    {
                        xnViewFields.InnerXml += childNode.InnerXml;
                    }
                }
                xnViewFields.InnerXml +=
                "<FieldRef Name = 'From'/>" +
                "<FieldRef Name = 'CC'/>" +
                "<FieldRef Name = 'BCC'/>";
                Listview.UpdateView(Sharepointlist.SelectedItem.ToString(), sDefaultViewName, null, null, xnViewFields, null, null, null);

                Syncpanel panel = new Syncpanel();
                panel.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


    }
}
